import ray
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# 初始化Ray
ray.init()

# 生成一些模拟的篮球运动员数据（示例数据）
np.random.seed(0)
X = np.random.rand(100, 2)  # 特征数据，例如身高和体重
y = np.random.choice([0, 1], size=100)  # 标签，1表示篮球运动员，0表示非篮球运动员

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 定义一个远程任务，用于训练模型
@ray.remote
def train_model(X_train, y_train):
    clf = RandomForestClassifier(n_estimators=100, random_state=42)
    clf.fit(X_train, y_train)
    return clf

# 并行训练多个模型
num_models = 5
model_refs = [train_model.remote(X_train, y_train) for _ in range(num_models)]

# 预测并评估多个模型
y_pred_list = []
for model_ref in model_refs:
    model = ray.get(model_ref)
    y_pred = model.predict(X_test)
    y_pred_list.append(y_pred)

# 汇总模型的预测结果
y_pred_combined = np.mean(y_pred_list, axis=0).round().astype(int)

# 计算合并模型的准确性
accuracy = accuracy_score(y_test, y_pred_combined)
print(f"合并模型的准确性: {accuracy}")

# 关闭Ray
ray.shutdown()
